package com.cheng.im.service.friendship.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cheng.im.common.bean.msg.ProtoMsgV1;
import com.cheng.im.common.constants.SeqConstants;
import com.cheng.im.service.common.eunms.ApproverFriendRequestStatusEnum;
import com.cheng.im.service.common.eunms.FriendShipErrorCode;
import com.cheng.im.service.common.exception.ApplicationException;
import com.cheng.im.service.common.resp.CommonResult;
import com.cheng.im.service.friendship.mapper.ImFriendshipRequestMapper;
import com.cheng.im.service.friendship.service.ImFriendshipRequestService;
import com.cheng.im.service.friendship.service.ImFriendshipService;
import com.cheng.im.service.frienship.domain.ImFriendshipRequest;
import com.cheng.im.service.frienship.model.req.ApproverFriendRequestReq;
import com.cheng.im.service.frienship.model.req.FriendDto;
import com.cheng.im.service.frienship.model.req.ReadFriendShipRequestReq;
import com.cheng.im.service.mq.RocketMQProduce;
import com.cheng.im.service.protobuilder.FriendshipRequestBuilder;
import com.cheng.im.service.redis.seq.RedisSeq;
import com.cheng.im.service.redis.seq.WriteUserSeq;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
* @author Cheng
* @description 针对表【im_friendship_request】的数据库操作Service实现
* @createDate 2024-12-17 15:04:33
*/
@DubboService
public class ImFriendshipRequestServiceImpl extends ServiceImpl<ImFriendshipRequestMapper, ImFriendshipRequest>
    implements ImFriendshipRequestService {

    @Resource
    private ImFriendshipService imFriendshipService;
    @Resource
    RedisSeq redisSeq;
    @Resource
    WriteUserSeq writeUserSeq;
    @Resource
    RocketMQProduce rocketMQProduce;

    @Override
    @Transactional
    public CommonResult addFriendshipRequest(String fromId, FriendDto dto, String appId) {
        LambdaQueryWrapper<ImFriendshipRequest> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ImFriendshipRequest::getAppId, appId);
        queryWrapper.eq(ImFriendshipRequest::getFromId, fromId);
        queryWrapper.eq(ImFriendshipRequest::getToId, dto.getToId());

        ImFriendshipRequest request = baseMapper.selectOne(queryWrapper);

        long seq = redisSeq.doGetSeq(appId+":"+ SeqConstants.FRIENDSHIP_REQUEST);

        if(request == null){
            request = new ImFriendshipRequest();
            request.setAddSource(dto.getAddSource());
            request.setAddWording(dto.getAddWording());
            request.setSequence(seq);
            request.setAppId(appId);
            request.setFromId(fromId);
            request.setToId(dto.getToId());
            request.setReadStatus(0);
            request.setApproveStatus(0);
            request.setRemark(dto.getRemark());
            request.setCreateTime(System.currentTimeMillis());
            request.setUpdateTime(System.currentTimeMillis());
            baseMapper.insert(request);

        }else {
            //修改记录内容 和更新时间
            if(StringUtils.isNotBlank(dto.getAddSource())){
                request.setAddWording(dto.getAddWording());
            }
            if(StringUtils.isNotBlank(dto.getRemark())){
                request.setRemark(dto.getRemark());
            }
            if(StringUtils.isNotBlank(dto.getAddWording())){
                request.setAddWording(dto.getAddWording());
            }
//            request.setSequence(seq);
            request.setApproveStatus(0);
            request.setReadStatus(0);
            request.setUpdateTime(System.currentTimeMillis());
            baseMapper.updateById(request);
        }

        writeUserSeq.writeUserSeq(appId, dto.getToId(), SeqConstants.FRIENDSHIP_REQUEST, seq);

        //发送好友申请的tcp给接收方
        ProtoMsgV1.Message msg = FriendshipRequestBuilder.build(request);

        // 发送给其他端
        rocketMQProduce.sendToUserExceptClient(fromId, msg);
        // 发送给对方
        rocketMQProduce.dispatchMessage(dto.getToId(), msg);

        return CommonResult.success();
    }

    @Override
    @Transactional
    public CommonResult approveFriendRequest(ApproverFriendRequestReq req) {
        ImFriendshipRequest imFriendShipRequestEntity = baseMapper.selectById(req.getId());

        if(imFriendShipRequestEntity == null){
            throw new ApplicationException(FriendShipErrorCode.FRIEND_REQUEST_IS_NOT_EXIST);
        }

        if(!req.getOperator().equals(imFriendShipRequestEntity.getToId())){
            // 只能审批发给自己的好友请求
            throw new ApplicationException(FriendShipErrorCode.NOT_APPROVER_OTHER_MAN_REQUEST);
        }

        long seq = redisSeq.doGetSeq(req.getAppId()+":"+ SeqConstants.FRIENDSHIP_REQUEST);

        ImFriendshipRequest update = new ImFriendshipRequest();
        update.setApproveStatus(req.getStatus());
        update.setUpdateTime(System.currentTimeMillis());
        update.setSequence(seq);
        update.setId(req.getId());
        baseMapper.updateById(update);

        writeUserSeq.writeUserSeq(req.getAppId(),req.getOperator(), SeqConstants.FRIENDSHIP_REQUEST, seq);

        if(ApproverFriendRequestStatusEnum.AGREE.getCode() == req.getStatus()){
            //同意 ===> 去执行添加好友逻辑
            FriendDto dto = new FriendDto();
            dto.setAddSource(imFriendShipRequestEntity.getAddSource());
            dto.setAddWording(imFriendShipRequestEntity.getAddWording());
            dto.setRemark(imFriendShipRequestEntity.getRemark());
            dto.setToId(imFriendShipRequestEntity.getToId());
            CommonResult responseVO = imFriendshipService.doAddFriend(req,imFriendShipRequestEntity.getFromId(), dto,req.getAppId());
//            if(!responseVO.isOk()){
////                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
//                return responseVO;
//            }
            if(!responseVO.isOk() && responseVO.getCode() != FriendShipErrorCode.TO_IS_YOUR_FRIEND.getCode()){
                return responseVO;
            }
        }

        // todo: 通知
//        ApproverFriendRequestPack approverFriendRequestPack = new ApproverFriendRequestPack();
//        approverFriendRequestPack.setId(req.getId());
//        approverFriendRequestPack.setSequence(seq);
//        approverFriendRequestPack.setStatus(req.getStatus());
//        messageProducer.sendToUser(imFriendShipRequestEntity.getToId(),req.getClientType(),req.getImei(), FriendshipEventCommand
//                .FRIEND_REQUEST_APPROVER,approverFriendRequestPack,req.getAppId());

        return CommonResult.success();
    }

    @Override
    public CommonResult readFriendShipRequestReq(ReadFriendShipRequestReq req) {
        LambdaQueryWrapper<ImFriendshipRequest> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendshipRequest::getAppId, req.getAppId());
        query.eq(ImFriendshipRequest::getToId, req.getFromId());

        long seq = redisSeq.doGetSeq(req.getAppId()+":"+ SeqConstants.FRIENDSHIP_REQUEST);

        ImFriendshipRequest update = new ImFriendshipRequest();
        update.setReadStatus(1);
        update.setSequence(seq);
        baseMapper.update(update, query);
        writeUserSeq.writeUserSeq(req.getAppId(),req.getOperator(), SeqConstants.FRIENDSHIP_REQUEST, seq);
        // todo:TCP通知
//        ReadAllFriendRequestPack readAllFriendRequestPack = new ReadAllFriendRequestPack();
//        readAllFriendRequestPack.setFromId(req.getFromId());
//        readAllFriendRequestPack.setSequence(seq);
//        messageProducer.sendToUser(req.getFromId(),req.getClientType(),req.getImei(),FriendshipEventCommand
//                .FRIEND_REQUEST_READ,readAllFriendRequestPack,req.getAppId());

        return CommonResult.success();
    }

    @Override
    public CommonResult<List<ImFriendshipRequest>> getFriendRequest(String fromId, String appId) {
        LambdaQueryWrapper<ImFriendshipRequest> query = new LambdaQueryWrapper<>();
        query.eq(ImFriendshipRequest::getAppId, appId);
        query.eq(ImFriendshipRequest::getFromId, fromId);

        List<ImFriendshipRequest> requestList = baseMapper.selectList(query);

        return CommonResult.success(requestList);
    }
}




